#include <Servo.h>
const int numOfServo = 6;
Servo servo[numOfServo];
String comdata = "";                                  //comdata用来存储读取的字符串
int numdata[numOfServo] = {0, 0, 0, 0, 0, 0}, mark = 0;  //numdata是将comdata拆分之后的数字数组
int holdDeg[numOfServo] = {40, 165, 180, 160, 35, 40};
int stretchDeg[numOfServo] = {180, 50, 40, 30, 150, 160};

void setup() {
  for (int i = 0; i < numOfServo; i++) {              //定义2至7脚是输出,依次为拇指、食指、中指、无名指、小指、大拇指关节
    servo[i].attach(i +2);
    servo[i].write(stretchDeg[i]);
    delay(300);
  }
  Serial.begin(9600);
}

void loop() {
  int j = 0;
  while (Serial.available() > 0) {
    char c = Serial.read();
    if (c == 'z') {
      mark = 1;
      break;
    }
    else if (c >= '0' && c <= '9' || c == ',') {
      comdata += c;                                
      delay(2);
    }
    else {
      comdata = "";
      while (Serial.read() >= 0);
    }
  }
  if (mark) {
    mark = 0;
    for (int i = 0; i < comdata.length(); i++)
      if (comdata[i] == ',') {
        j++;
      } else {
        numdata[j] = numdata[j] * 10 + (comdata[i] - '0');                              //
      }
    comdata = String("");                                                              //
    if (j == 5)
      {
      for (int i = 0; i < 5; i++) {
        servo[i].write(map(numdata[i], 0, 100, holdDeg[i], stretchDeg[i])); 
                       
        //numdata[i] = 0;                                                                  //
      }
      servo[5].write(map(numdata[0], 0, 100, holdDeg[5], stretchDeg[5]));                       //大拇指关节舵机输出大拇指舵机的数据
      for (int i = 0; i < 5; i++) { 
        numdata[i] = 0; 
      }
       
      }
  }
}
